package prj.carmap.mobile.activity;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import prj.carmap.mobile.model.SellerInfo;
import prj.carmap.mobile.process.BMapGeneralListener;
import prj.carmap.mobile.util.BMapUtil;
import prj.carmap.mobile.view.ZoomControlView;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockActivity;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * 演示覆盖物的用法
 */
@SuppressLint("NewApi")
public class MapOverlayActivity extends SherlockActivity {
	private static AsyncHttpClient client = new AsyncHttpClient();

	/**
	 *  MapView 是地图主控件
	 */
	private MapView mMapView = null;
	/**
	 *  用MapController完成地图控制 
	 */
	private MapController mMapController = null;
	private MyOverlay mOverlay = null;
	private PopupOverlay   pop  = null;
	private ArrayList<OverlayItem>  mItems = null; 
	private TextView  popupText = null;
	private View viewCache = null;
	private View popupInfo = null;
	private Button button = null;
	private MapView.LayoutParams layoutParam = null;
	private OverlayItem mCurItem = null;
	/*ArrayList<String> longitudeAarray;
	ArrayList<String> latitudeAarray;
	ArrayList<String> sellerAarray;
	ArrayList<String> type;*/

	private ZoomControlView mZoomControlView;
	
	private Button list;
	private String content;

	/** 百度地图管理器 */
	private BMapManager bMapManager;
	private ArrayList<SellerInfo> sellers;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (bMapManager == null) {
			bMapManager = new BMapManager(getApplicationContext());
			bMapManager.init(CarmapApplication.strKey, new BMapGeneralListener(
					CarmapApplication.getInstance()));
		}
        CarmapApplication.addActivity(this);
        /**
         * 由于MapView在setContentView()中初始化,所以它需要在BMapManager初始化之后
         */
        setContentView(R.layout.activity_overlay);
        Button returnBtn = (Button) findViewById(R.id.return_prev);
		returnBtn.setOnClickListener(new Button.OnClickListener() {// 创建监听
					public void onClick(View v) {
						MapOverlayActivity.this.finish();
					}
				});
        list = (Button) findViewById(R.id.list);
        list.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
        mMapView = (MapView)findViewById(R.id.bmapView);
        /**
         * 获取地图控制器
         */
        mMapController = mMapView.getController();
        /**
         *  设置地图是否响应点击事件  .
         */
        mMapController.enableClick(true);
        /**
         * 设置地图缩放级别
         */
        mMapController.setZoom(14);
        /**
         * 显示内置缩放控件
         */
        mMapView.setBuiltInZoomControls(false);
        

		mZoomControlView = (ZoomControlView) findViewById(R.id.OverlayZoomControlView);
		mZoomControlView.setMapView(mMapView);
		
   	    String typeId = getIntent().getStringExtra("typeId");
   	    if(typeId!=null&&!typeId.equals("")){
			content = this.getIntent().getStringExtra("content");
			client.get(CarmapApplication.SERVER_URL + "/rest/seller/bytype/"+typeId,
					new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(String content) {
					 double lon=0.0;
					  double lat=0.0;
					try {
						JSONArray jsonAry = new JSONArray(content);
						sellers = new ArrayList<SellerInfo>();
						for (int i = 0; i < jsonAry.length(); i++) {
							JSONObject json = jsonAry.getJSONObject(i);
							sellers.add(SellerInfo.fromJson(json));
						}
						 /**
				         * 设定地图中心点
				         */
				      //  for(int i=0;i<sellers.size();i++){
						if(sellers!=null&&sellers.size()>0){
							SellerInfo si = sellers.get(0);
							lon=si.longitude;
							lat = si.latitude;
						}
						initOverlay();
				        GeoPoint p = new GeoPoint((int)(lat * 1E6), (int)(lon* 1E6));
				        mMapController.setCenter(p);
				      //  }
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			});
   	  }else{
   		  try {
   			  double lat = Double.parseDouble( getIntent().getStringExtra("lat"));
   			  double lon = Double.parseDouble(getIntent().getStringExtra("lon"));
   			  String name = getIntent().getStringExtra("name");
   			  initDefault((int)(lat*1E6), (int)(lon*1E6), name);
   			  GeoPoint p = new GeoPoint((int)(lat*1E6), (int)(lon*1E6));
   			  mMapController.setCenter(p);
		} catch (Exception e) {
			e.printStackTrace();
		}
   	  }
		
       /* longitudeAarray = getIntent().getStringArrayListExtra("longitudeAarray");
        latitudeAarray = getIntent().getStringArrayListExtra("latitudeAarray");
        sellerAarray = getIntent().getStringArrayListExtra("sellerAarray");
        type = getIntent().getStringArrayListExtra("superSellerType");*/
       
        
    }
  
	private void refreshScaleAndZoomControl() {
		// 更新缩放按钮的状态
		Log.i("sss", "level" + mMapView.getZoomLevel());
		mZoomControlView.refreshZoomButtonStatus(Math.round(mMapView
				.getZoomLevel()));

	}
	
	public void initDefault(int mLat1,int mLon1,String name){
         mOverlay = new MyOverlay(getResources().getDrawable(R.drawable.icon_gcoding_1),mMapView);	
         GeoPoint p1 = new GeoPoint (mLat1,mLon1);
		 OverlayItem item1 = new OverlayItem(p1,name+",21","");
		 item1.setMarker(getResources().getDrawable(R.drawable.icon_marka_red));
		 mOverlay.addItem(item1);
		 
         LocationData loactionData= CarmapApplication.getInstance().getLocData();
         GeoPoint p2 = new GeoPoint ((int)(loactionData.latitude*1E6),(int)(loactionData.longitude*1E6));
         OverlayItem item2 = new OverlayItem(p2,"我的位置","");
         item2.setMarker(getResources().getDrawable(R.drawable.navi_map_gps_locked));
         mOverlay.addItem(item2);
         /**
          * 保存所有item，以便overlay在reset后重新添加
          */
         mItems = new ArrayList<OverlayItem>();
         mItems.addAll(mOverlay.getAllItem());


         /**
          * 将overlay 添加至MapView中
          */
         mMapView.getOverlays().add(mOverlay);
         /**
          * 刷新地图
          */
         mMapView.refresh();
         /**
          * 向地图添加自定义View.
          */
         viewCache = getLayoutInflater().inflate(R.layout.custom_text_view, null);
         popupInfo = (View) viewCache.findViewById(R.id.popinfo);
         popupText =(TextView) viewCache.findViewById(R.id.textcache);
         
         button = new Button(this);
         button.setBackgroundResource(R.drawable.popup);
         PopupClickListener popListener = new PopupClickListener(){
 			@Override
 			public void onClickedPopup(int index) {
 				
 			}
         };
         pop = new PopupOverlay(mMapView,popListener); 
  		refreshScaleAndZoomControl();
         
	}
    
    public void initOverlay(){
    	 
    	/**
    	 * 创建自定义overlay
    	 */
         mOverlay = new MyOverlay(getResources().getDrawable(R.drawable.icon_gcoding_1),mMapView);	
         /**
          * 准备overlay 数据
          */
         
         for(int i =0;i<sellers.size();i++){
        	 SellerInfo si = sellers.get(i);
        			 double mLon1=si.longitude;
        			 double mLat1=si.latitude;
        			 GeoPoint p1 = new GeoPoint ((int)(mLat1*1E6),(int)(mLon1*1E6));
        			 String t=si.superSellerType;
        			 OverlayItem item1 = new OverlayItem(p1,si.sellerName+","+t,si.sellerId);
        			 /**
        			  * 设置overlay图标，如不设置，则使用创建ItemizedOverlay时的默认图标.
        			  */
        			 if (t.equals("21")) {
 						item1.setMarker(getResources().getDrawable(
 								R.drawable.icon_marka_red));
 					} else if (t.equals("27")) {
 						item1.setMarker(getResources().getDrawable(
 								R.drawable.icon_marka_red));
 					}
        			/* MyView mv = new MyView();
        			 Drawable dr = getResources().getDrawable(R.drawable.icon_gcoding);
        			 Bitmap bitmap = Bitmap.createBitmap(dr.getIntrinsicWidth(),
        					 dr.getIntrinsicHeight(),
        					 dr.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                             : Bitmap.Config.RGB_565);
        			 mv.setBitmap(bitmap);
        			 mv.setNum(0);
        			 item1.setMarker(mv);*/
        			 mOverlay.addItem(item1);
         }
         LocationData loactionData= CarmapApplication.getInstance().getLocData();
         GeoPoint p2 = new GeoPoint ((int)(loactionData.latitude*1E6),(int)(loactionData.longitude*1E6));
         OverlayItem item2 = new OverlayItem(p2,"我的位置","");
         item2.setMarker(getResources().getDrawable(R.drawable.navi_map_gps_locked));
         mOverlay.addItem(item2);
         /**
          * 保存所有item，以便overlay在reset后重新添加
          */
         mItems = new ArrayList<OverlayItem>();
         mItems.addAll(mOverlay.getAllItem());


         /**
          * 将overlay 添加至MapView中
          */
         mMapView.getOverlays().add(mOverlay);
         /**
          * 刷新地图
          */
         mMapView.refresh();
         /**
          * 向地图添加自定义View.
          */
         viewCache = getLayoutInflater().inflate(R.layout.custom_text_view, null);
         popupInfo = (View) viewCache.findViewById(R.id.popinfo);
         popupText =(TextView) viewCache.findViewById(R.id.textcache);
         
         button = new Button(this);
         button.setBackgroundResource(R.drawable.popup);
         
         /**
          * 创建一个popupoverlay
          */
         PopupClickListener popListener = new PopupClickListener(){
			@Override
			public void onClickedPopup(int index) {
				client.get(CarmapApplication.SERVER_URL + "/rest/seller/" + mCurItem.getSnippet(),
						new AsyncHttpResponseHandler() {
							public void onSuccess(String content) {
								try
								{
									JSONObject json = new JSONObject(content);
									Intent intent = new Intent(MapOverlayActivity.this, SellerActivity.class);
									intent.putExtra("currentSeller", SellerInfo.fromJson(json));
									MapOverlayActivity.this.startActivity(intent);
									pop.hidePop();
								}
								catch (JSONException e) {
									e.printStackTrace();
								}
							}

							public void onFailure(Throwable error, String content) {
								pop.hidePop();
							}
						});
			}
         };
         pop = new PopupOverlay(mMapView,popListener);
         
 		refreshScaleAndZoomControl();
    }
    /**
     * 清除所有Overlay
     * @param view
     */
    public void clearOverlay(View view){
    	mOverlay.removeAll();
    	if (pop != null){
            pop.hidePop();
    	}
    	mMapView.removeView(button);
    	mMapView.refresh();
    }
    /**
     * 重新添加Overlay
     * @param view
     */
    public void resetOverlay(View view){
    	//重新add overlay
    	mOverlay.addItem(mItems);
    	mMapView.refresh();
    }
   
    @Override
    protected void onPause() {
    	/**
    	 *  MapView的生命周期与Activity同步，当activity挂起时需调用MapView.onPause()
    	 */
        mMapView.onPause();
        super.onPause();
    }
    
    @Override
    protected void onResume() {
    	/**
    	 *  MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
    	 */
        mMapView.onResume();
        super.onResume();
    }
    
    @Override
    protected void onDestroy() {
    	/**
    	 *  MapView的生命周期与Activity同步，当activity销毁时需调用MapView.destroy()
    	 */
        mMapView.destroy();
        super.onDestroy();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    	mMapView.onSaveInstanceState(outState);
    	
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
    	mMapView.onRestoreInstanceState(savedInstanceState);
    }
    
    public class MyOverlay extends ItemizedOverlay{

		public MyOverlay(Drawable defaultMarker, MapView mapView) {
			super(defaultMarker, mapView);
		}
		

		@Override
		public boolean onTap(int index){
			OverlayItem item = getItem(index);
			mCurItem = item ;
		   if(getItem(index).getTitle().equals("我的位置")){
			   popupText.setText(getItem(index).getTitle());
			   popupText.setBackground(getResources().getDrawable(
						R.drawable.popup_middle));
		   }else{
			   popupText.setText(getItem(index).getTitle().split(",")[0]);
			   if (getItem(index).getTitle().split(",")[1].equals("21")) {
					popupText.setBackground(getResources().getDrawable(
							R.drawable.popup_middle_red));
				} else if (getItem(index).getTitle().split(",")[1].equals("27")) {
					popupText.setBackground(getResources().getDrawable(
							R.drawable.popup_middle_red));
				}
		   }
		   Bitmap[] bitMaps={
			    BMapUtil.getBitmapFromView(popupInfo), 		
		    };
		    pop.showPopup(bitMaps,item.getPoint(),32);
			return true;
		}
		
		@Override
		public boolean onTap(GeoPoint pt , MapView mMapView){
			if (pop != null){
                pop.hidePop();
                mMapView.removeView(button);
			}
			return false;
		}
    	
    }
    
    
    public SQLiteDatabase openDatabase(String name, int mode, CursorFactory factory){
    	return openOrCreateDatabase(name ,mode,factory);
    }
}
